//
//  HD_HSP_Player_ViewController.m
//  HDLiaoNingMeseum
//
//  Created by HDHaoShaoPeng on 2017/8/5.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_HSP_Player_ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface HD_HSP_Player_ViewController ()<AVAudioSessionDelegate>
@property (weak, nonatomic) IBOutlet UILabel *audioCurrentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *audioLeftTimeLabel;

@property (strong, nonatomic) IBOutlet UIWebView *myWebView;
@property (weak, nonatomic) IBOutlet UISlider *audioSlider;
@property (weak, nonatomic) IBOutlet UIButton *audioControlButton;
@property (weak, nonatomic) IBOutlet UIView *localView;
@property (weak, nonatomic) IBOutlet UIWebView *urlWebView;


@property (weak, nonatomic) IBOutlet UILabel *myTitleLabel;


- (IBAction)updateCurrentTime:(UISlider *)sender;
- (IBAction)audioControlAction:(UIButton *)sender;
- (void)updateSliderValue;

@property (strong, nonatomic) id timeObserver;
@property (strong, nonatomic) AVPlayer *audioPlayer;

@end

static HDDeclare *declare;

@implementation HD_HSP_Player_ViewController

{
    BOOL       audioPlaying;
    BOOL       enterBgPlaying;
}

- (void) awakeFromNib
{
    [super awakeFromNib];
    
    _audioPlayer = [[AVPlayer alloc]init];
    declare = [HDDeclare sharedDeclare];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.myTitleLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:18.0];
    
    
    [self.audioSlider setThumbImage:[UIImage imageNamed:@"slider_button"] forState:UIControlStateNormal];
    [self.audioSlider setThumbImage:[UIImage imageNamed:@"slider_button"] forState:UIControlStateHighlighted];
    
    UIView *tapView = [[UIView alloc] initWithFrame:CGRectMake(self.audioSlider.frame.origin.x, self.audioSlider.frame.origin.y-5, self.audioSlider.frame.size.width, 44)];
    [tapView setBackgroundColor:[UIColor clearColor]];
    [tapView setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTap:)];
    [tapView addGestureRecognizer:tap];
    [self.audioSlider addGestureRecognizer:tap];
    [self.view insertSubview:tapView belowSubview:self.audioSlider];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backFromBackground) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backToBackground) name:UIApplicationWillResignActiveNotification object:nil];
    
    [self uploadBrowsingHistory];
}

-(void)uploadBrowsingHistory
{
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],@"index.php?g=mapi&m=User&a=visit_records"];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:declare.userID,@"device_id",self.detailItem.FileNum,@"exhibit_id",[NSString stringWithFormat:@"%ld",(long)declare.languageIndex],@"language", nil];
    [HD_LY_NetHelper requestWithType:POST withUrl:requestUrl withParams:params toShowVC:self success:^(id response) {
        NSDictionary *dicData = response;
        if ([dicData[@"status"] intValue] == 1)
        {
        }else
        {
        }
    } fail:^(NSError *error) {
        
    } showHUD:NO isCache:YES];
}

- (void) sliderTap:(UITapGestureRecognizer *)gesture
{
    CGPoint point = [gesture locationInView:self.view];
    double duration = CMTimeGetSeconds([self.audioPlayer.currentItem duration]);
    double ratio = (point.x - self.audioSlider.frame.origin.x)/self.audioSlider.frame.size.width;
    double currentTime = floor(duration*ratio);
    
    if (currentTime >= duration)
    {
        [self back];
        return;
    }
    
    if (isfinite(duration))
    {
        [self removeTimeObserverFromPlayer];
        float  _playRateToRestore = [self.audioPlayer rate];
        [self.audioPlayer setRate:0.0];
        [self.audioSlider setValue:ratio];
        [self.audioPlayer seekToTime:CMTimeMakeWithSeconds(currentTime, NSEC_PER_SEC)];
        [self.audioPlayer setRate:_playRateToRestore];
        [self addTimeObserverToPlayer];
    }
    
    if (audioPlaying)
        return;
    
    double seconds = CMTimeGetSeconds([self.audioPlayer currentTime]);
    if (isfinite(seconds))
    {
        if (seconds < 0.0)
        {
            seconds = 0.0;
        }
        int secondsInt = round(seconds);
        int minutes = secondsInt/60;
        int minutesOnes = minutes%10;
        int minutesTens = minutes/10;
        secondsInt -= minutes*60;
        int secondsOnes = secondsInt%10;
        int secondsTens = secondsInt/10;
        
        _audioCurrentTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [self hasMicphone];
    declare.visibleVC = self.navigationController.visibleViewController;
    
    if (declare.netStatus) {
        self.localView.hidden = NO;
        [self initPlayAudioMethod];
    }
    else
    {
        self.urlWebView.hidden = NO;
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],self.detailItem.FileNum];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.urlWebView loadRequest:request];
    }
    
    
    [super viewDidAppear:animated];

}

-(void)initPlayAudioMethod
{
    [self playItem:self.detailItem];
    
    //playn文件编号（8位）
    NSString *filePath = [NSString stringWithFormat:@"%@/0106/0106.html",declare.catch_path];//[NSString stringWithFormat:@"%@/%@/%@/%@.html",declare.catch_path,[declare.language uppercaseString], self.detailItem.FileNum, self.detailItem.FileNum];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [_myWebView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
    _myWebView.opaque = NO;
    
    AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleInterruption:)
                                                 name:AVAudioSessionRouteChangeNotification
                                               object:audioSessionobj];
}

- (void)handleInterruption:(NSNotification *)sender
{
    //AVAudioSessionRouteChangeReasonKey = 1;// 插入耳机
    //AVAudioSessionRouteChangeReasonKey = 2;// 拔出耳机
    AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
    NSError *error = nil;
    NSDictionary *myDic = sender.userInfo;
    NSInteger micphoneIndex = [[myDic valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    if (audioPlaying == YES && micphoneIndex == 2)
    {
        [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];
        [self audioControlAction:nil];
    }
    else if ( micphoneIndex == 2)
    {
        [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];
    }
    else if ( micphoneIndex == 1)
    {
        [audioSessionobj setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self.audioPlayer pause];
    [self.audioControlButton setImage:[UIImage imageNamed:@"audio_play_button"] forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)backFromBackground
{
    if (enterBgPlaying == YES)
    {
        [self audioControlAction:nil];
    }
}

- (void)backToBackground
{
    if (audioPlaying == YES)
    {
        [self audioControlAction:nil];
        enterBgPlaying = YES;
    }
    else if (audioPlaying == NO)
    {
        enterBgPlaying = NO;
    }
}

#pragma mark - ------- Audio Methods --------

- (void)addTimeObserverToPlayer
{
    if (self.timeObserver)
        return;
    
    double interval = 0.1;
    CMTime time = [self.audioPlayer.currentItem duration];
    double duration = CMTimeGetSeconds(time);
    if (isfinite(duration))
    {
        CGFloat width = CGRectGetWidth([self.audioSlider bounds]);
        interval = 0.5 * duration / width;
    }
    __block __weak HD_HSP_Player_ViewController *player = self;
    self.timeObserver = [self.audioPlayer addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(interval, NSEC_PER_SEC)
                                                                       queue:dispatch_get_main_queue()
                                                                  usingBlock:^(CMTime time){
                                                                      [player updateSliderValue];
                                                                  }];
}

-(void)updateSliderValue
{
    double duration = CMTimeGetSeconds([self.audioPlayer.currentItem duration]);
    int secondsInt = round(duration);
    int minutes = secondsInt/60;
    int minutesOnes = minutes%10;
    int minutesTens = minutes/10;
    secondsInt -= minutes*60;
    int secondsOnes = secondsInt%10;
    int secondsTens = secondsInt/10;
    
    _audioLeftTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
    if (isfinite(duration))
    {
        double time = CMTimeGetSeconds([self.audioPlayer currentTime]);
        
        [self.audioSlider setValue:time / duration];
        if (time+0.1 >= duration)
        {
            [self back];
        }
    }
    
    double seconds = CMTimeGetSeconds([self.audioPlayer currentTime]);
    if (isfinite(seconds))
    {
        if (seconds < 0.0)
        {
            seconds = 0.0;
        }
        int secondsInt = round(seconds);
        int minutes = secondsInt/60;
        int minutesOnes = minutes%10;
        int minutesTens = minutes/10;
        secondsInt -= minutes*60;
        int secondsOnes = secondsInt%10;
        int secondsTens = secondsInt/10;
        
        _audioCurrentTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
    }
}

-(void)stopAudio
{
    [self.audioPlayer pause];
    self.audioPlayer = nil;
    audioPlaying = NO;
    [self removeTimeObserverFromPlayer];
    self.audioSlider.value = 0;
    self.audioLeftTimeLabel.text = @"00:00";
    self.audioCurrentTimeLabel.text = @"00:00";
    
    BOOL success = NO;
    NSError *error = nil;
    AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
//    if ([[HDDeclare sharedDeclare] autoFlag] == NO)
//        [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];
    
    success =[audioSessionobj setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    if (!success)
    {
        LOG(@"Error setting category: %@", [error localizedDescription]);
        return;
    }
    success= [audioSessionobj setActive:true error:&error];
    if (!success)
    {
        LOG(@"Error setting category: %@", [error localizedDescription]);
        return;
    }
}

- (void)removeTimeObserverFromPlayer
{
    if (self.timeObserver)
    {
        [self.audioPlayer removeTimeObserver:self.timeObserver];
        self.timeObserver = nil;
    }
}

-(void)playItem:(HD_HSP_Exhibit_Model *)item
{
    self.title = item.FileName;
    
    if (audioPlaying)
    {
        [self stopAudio];
    }
    [self playAudio:item];
}

-(void)playAudio:(HD_HSP_Exhibit_Model *)item
{
    self.detailItem = item;
    
    //playn文件编号（8位）
    NSString *audioPath = [NSString stringWithFormat:@"%@/0106/0106.mp3",declare.catch_path];//[NSString stringWithFormat:@"%@/%@/%@/%@.mp3",declare.catch_path,[declare.language uppercaseString],item.FileNum,item.FileNum];
    
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    _audioPlayer = [[AVPlayer alloc]initWithURL:audioURL];
    
    BOOL success = NO;
    NSError *error = nil;
    AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
    success =[audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];

    
    if (!success)
    {
        LOG(@"Error setting category: %@", [error localizedDescription]);
        return;
    }
    success= [audioSessionobj setActive:true error:&error];
    if (!success)
    {
        LOG(@"Error setting category: %@", [error localizedDescription]);
        return;
    }
    
    
    CMTime time = [self.audioPlayer.currentItem duration];
    double duration = CMTimeGetSeconds(time);
    if (isfinite(duration))
    {
        if (duration < 0.0)
        {
            duration = 0.0;
        }
        int secondsInt = round(duration);
        int minutes = secondsInt/60;
        int minutesOnes = minutes%10;
        int minutesTens = minutes/10;
        secondsInt -= minutes*60;
        int secondsOnes = secondsInt%10;
        int secondsTens = secondsInt/10;
        
        _audioLeftTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
    }
    
    
    [self.audioPlayer play];
    audioPlaying = YES;
    [self.audioControlButton setImage:[UIImage imageNamed:@"audio_pasue_button"] forState:UIControlStateNormal];
    [self addTimeObserverToPlayer];
}

#pragma mark
#pragma mark -------- Other Methods --------

- (IBAction)updateCurrentTime:(UISlider *)sender
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.audioSlider.value >= 1.0)
        {
            [self back];
            return;
        }
        double duration = CMTimeGetSeconds([self.audioPlayer.currentItem duration]);
        
        if (isfinite(duration))
        {
            float value = [sender value];
            double time = duration*value;
            [self removeTimeObserverFromPlayer];
            float  _playRateToRestore = [self.audioPlayer rate];
            [self.audioPlayer setRate:0.0];
            [self.audioPlayer seekToTime:CMTimeMakeWithSeconds(time, NSEC_PER_SEC)];
            [self.audioPlayer setRate:_playRateToRestore];
            [self addTimeObserverToPlayer];
        }
        
        if (audioPlaying)
            return;
        
        double seconds = CMTimeGetSeconds([self.audioPlayer currentTime]);
        if (isfinite(seconds))
        {
            if (seconds < 0.0)
            {
                seconds = 0.0;
            }
            int secondsInt = round(seconds);
            int minutes = secondsInt/60;
            int minutesOnes = minutes%10;
            int minutesTens = minutes/10;
            secondsInt -= minutes*60;
            int secondsOnes = secondsInt%10;
            int secondsTens = secondsInt/10;
            
            _audioCurrentTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
        }
    });
}

- (IBAction)audioControlAction:(UIButton *)sender
{
    if (audioPlaying)
    {
        [self.audioPlayer pause];
        audioPlaying = NO;
        [self.audioControlButton setImage:[UIImage imageNamed:@"audio_play_button"] forState:UIControlStateNormal];
        [self removeTimeObserverFromPlayer];
    }
    else
    {
        AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
        NSError *error = nil;
        [audioSessionobj setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
//        if ([[HDDeclare sharedDeclare] autoFlag] == NO || [self hasMicphone] == NO)
//            [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];
        
        [self.audioPlayer play];
        audioPlaying = YES;
        [self.audioControlButton setImage:[UIImage imageNamed:@"audio_pasue_button"] forState:UIControlStateNormal];
        [self addTimeObserverToPlayer];
    }
}

- (BOOL)hasMicphone
{
    if ([[AVAudioSession sharedInstance] isInputAvailable] == NO)
        return NO;
    
    // 判断是否有耳机
    AVAudioSessionRouteDescription *des = [[AVAudioSession sharedInstance] currentRoute];
    NSArray *a = des.outputs;
    for (AVAudioSessionPortDescription *s in a) {
        if ([s.portType isEqualToString:AVAudioSessionPortHeadsetMic] || [s.portType isEqualToString:AVAudioSessionPortHeadphones]) {
            NSLog(@"耳机");
            return YES;
        }
    }
    
    return NO;
}

#pragma mark
#pragma mark -------- Dealloc Methods --------

-(void)back
{
    [self stopAudio];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [self setAudioCurrentTimeLabel:nil];
    [self setAudioLeftTimeLabel:nil];
    
    [self setAudioSlider:nil];
    [self setAudioControlButton:nil];
    [super viewDidUnload];
}

-(void)dealloc
{
    [self stopAudio];
    
//    self.currentResource = nil;
//    self.itemArray = nil;
    
    self.timeObserver = nil;
    self.audioPlayer = nil;
}



- (IBAction)backClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


@end
